package Dao

import (
	"fmt"
	"github.com/garyburd/redigo/redis"
	"github.com/pkg/errors"
	"server5/Bean"
	"server5/utils"
	"strconv"
)

type UserDao struct {
	Pool *utils.RedisConnPool
}

var userDao *UserDao

//单例模式
func GetUserDao() *UserDao {
	if userDao == nil {
		return &UserDao{Pool: utils.RedisPool}
	}
	return userDao
}

//添加用户,注册功能
func (u *UserDao) AddUserInfo(name, pwd string) (ok bool, err error) {
	conn := u.Pool.Pool.Get()
	defer conn.Close()

	n, err := redis.Int(conn.Do("HLEN", "User_"+name))
	if n > 0 {
		return false, err
	}

	_, err = conn.Do("HMSET", "User_"+name,
		"Pwd", pwd,
		"Lv", 1,
		"Exp", 0,
		"Sp", 3,
		"Gold", 300,
		"ReplayHpLevel", 3,
		"DamageLevel", 3,
		"CallBossLevel", 3,
		"InfantryLevel", 3,
		"ArcherLevel", 3,
		"MageLevel",3,
	)

	return true, err
}

//删除用户
func (u *UserDao) DelUser(name string) (err error) {
	conn := u.Pool.Pool.Get()
	defer conn.Close()

	_, err = redis.Int(conn.Do("DEL", "User_"+name))
	if err != nil {
		if err == redis.ErrNil {
			fmt.Println("用户不存在")
		}
		err = errors.WithStack(err)
	}
	return
}

//查找用户
func (u *UserDao) FindUserInfo(name string) (user Bean.UserInfo, err error) {
	conn := u.Pool.Pool.Get()
	defer conn.Close()

	result, err := redis.Strings(conn.Do("HVALS", "User_"+name))
	if err != nil {
		if err == redis.ErrNil {
			fmt.Println("用户不存在")
		}
		return
	}
	if len(result) != 11 {
		fmt.Println("数据库错误，玩家信息不完整")
		return
	} else {
		user.UserName = name
		user.UserPwd = result[0]
		user.UserLv, _ = strconv.Atoi(result[1])
		user.UserExp, _ = strconv.Atoi(result[2])
		user.UserSp, _ = strconv.Atoi(result[3])
		user.UserGold, _ = strconv.Atoi(result[4])
		user.ReplyHpLevel, _ = strconv.Atoi(result[5])
		user.DamageLevel, _ = strconv.Atoi(result[6])
		user.CallBossLevel, _ = strconv.Atoi(result[7])
		user.ArcherLevel, _ = strconv.Atoi(result[8])
		user.InfantryLevel, _ = strconv.Atoi(result[9])
		user.MageLevel, _ = strconv.Atoi(result[10])
	}
	return
}

//更新用户信息
func (u *UserDao) UpdateUser(newUser Bean.UserInfo) (result string) {
	conn := u.Pool.Pool.Get()
	defer conn.Close()

	result, err := redis.String(conn.Do("HMSET", "User_" + newUser.UserName,
		"Lv", newUser.UserLv,
		"Exp", newUser.UserExp,
		"Sp", newUser.UserSp,
		"Gold", newUser.UserGold,
		"ReplayHpLevel", newUser.ReplyHpLevel,
		"DamageLevel", newUser.DamageLevel,
		"CallBossLevel", newUser.CallBossLevel,
		"InfantryLevel", newUser.InfantryLevel,
		"ArcherLevel", newUser.ArcherLevel,
		"MageLevel",newUser.MageLevel),
	)

	if err != nil {
		if err == redis.ErrNil {
			fmt.Println("用户不存在")
		}
		return "更新失败"
	}
	return result
}
